﻿using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Lottery.Client.SL.Controls
{
    public partial class SearchUserWindow : ChildWindow
    {
        #region Delegates

        public delegate void SearchUserHandler(object sender, string username);

        #endregion

        private SearchUserHandler _searchUserHandler;

        public SearchUserWindow()
        {
            InitializeComponent();
            base.KeyUp += (Base_Keyup);
            tbUserName.KeyUp += (tbUserName_Keyup);
            DataCache.ChildWindowObject = this;
        }

        public event SearchUserHandler SearchUser
        {
            add
            {
                SearchUserHandler searchUserHandler = _searchUserHandler;
                SearchUserHandler searchUserHandler2;
                do
                {
                    searchUserHandler2 = searchUserHandler;
                    var searchUserHandler3 = (SearchUserHandler) Delegate.Combine(searchUserHandler2, value);
                    searchUserHandler = Interlocked.CompareExchange(ref _searchUserHandler, searchUserHandler3,
                                                                    searchUserHandler2);
                } while (searchUserHandler != searchUserHandler2);
            }
            remove
            {
                SearchUserHandler searchUserHandler = _searchUserHandler;
                SearchUserHandler searchUserHandler2;
                do
                {
                    searchUserHandler2 = searchUserHandler;
                    var searchUserHandler3 = (SearchUserHandler) Delegate.Remove(searchUserHandler2, value);
                    searchUserHandler = Interlocked.CompareExchange(ref _searchUserHandler, searchUserHandler3,
                                                                    searchUserHandler2);
                } while (searchUserHandler != searchUserHandler2);
            }
        }

        private void tbUserName_Keyup(object sender, KeyEventArgs keyEventArgs)
        {
            if (Key.Enter == keyEventArgs.Key)
            {
                btnFindUser_Click(sender, keyEventArgs);
            }
        }

        private void Base_Keyup(object obj, KeyEventArgs keyEventArgs)
        {
            if (Key.Escape == keyEventArgs.Key)
            {
                base.DialogResult = false;
            }
        }

        private void btnFindUser_Click(object sender, RoutedEventArgs e)
        {
            if (_searchUserHandler != null)
            {
                _searchUserHandler(this, tbUserName.Text);
            }
            base.DialogResult = true;
        }
    }
}